package afss.freesky.data.util;

import java.sql.SQLException;

import org.apache.log4j.Logger;

import afss.freesky.data.conn.DBConnBean;


/**
 * @author <b>Jacky Chou</b> (Copyright &#169; 2005~2010 AFSS [Amei's FreeSky
 *         Studio])
 * @version 1.2.0, 2008-02-23, Upgrade freesky.jar to 1.2.0 with Struts 2 <br>
 *          1.0.0, 2006-05-30, Initial Version
 */
public class DeleteHelper extends TableHelper {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(DeleteHelper.class);

	public DeleteHelper() {
		this.opType = DBType.OP_DELETE;
	}

	public DeleteHelper(DBConnBean conn) {
		super(conn);
		this.opType = DBType.OP_DELETE;
	}

	public DeleteHelper(DBConnBean conn, String tableName) {
		super(conn, tableName);
		this.opType = DBType.OP_DELETE;
	}

	public DeleteHelper(DBConnBean conn, String tableName, String opType) {
		super(conn, tableName, opType);

	}

	public String getSQL() {
		if (this.whereList == null || this.whereList.size() == 0)
			return null;
		String pre = "DELETE FROM " + this.tableName;
		String condition = " WHERE ";

		// construt where condition
		for (int i = 0; i < this.whereList.size(); i++) {
			FieldValueBean bean = (FieldValueBean) whereList.get(i);
			if (bean.getValue() != null) {
				if (i != 0)
					condition += " AND ";

				if (bean.getType().equals(DBType.F_STRING)) {
					condition += bean.getField() + "='" + bean.getValue() + "'";
				} else if (bean.getType().equals(DBType.F_INTEGER)) {
					condition += bean.getField() + "=" + bean.getValue();
				} else if (bean.getType().equals(DBType.F_DOUBLE)) {
					condition += bean.getField() + "=" + bean.getValue();
				}
			}
		}

		String sql = pre + condition;
		if (logger.isDebugEnabled()) {
			logger.debug("getSQL() - String sql=" + sql);
		}

		return sql;
	}

	public int execute() {
		if (conn == null)
			return 0;
		try {
			String sql = getSQL();
			return conn.executeUpdate(sql);
		} catch (SQLException e) {
			logger.error(
					"execute() - Error occured when execute SQL statement:", e);
		}
		return 0;
	}
}
